include(ExternalProject)

# openssl
set(OPENSSL_LIB_SUFFIX ${CMAKE_STATIC_LIBRARY_SUFFIX})

set(OPENSSL_BUNDLE_DIR "${PROJECT_BINARY_DIR}")
set(OPENSSL_INCLUDE_DIR "${PROJECT_BINARY_DIR}/include/")
set(OPENSSL_LIBRARY_SSL "${PROJECT_BINARY_DIR}/lib/libssl${OPENSSL_LIB_SUFFIX}")
set(OPENSSL_LIBRARY_CRYPTO "${PROJECT_BINARY_DIR}/lib/libcrypto${OPENSSL_LIB_SUFFIX}")
set(OPENSSL_LIBRARIES ${OPENSSL_LIBRARY_SSL} ${OPENSSL_LIBRARY_CRYPTO})
#set(CMAKE_ANDROID_NDK /Users/finger/Library/Android/sdk/ndk/25.2.9519653)

message(STATUS "Using bundled openssl in '${OPENSSL_BUNDLE_DIR}'")

ExternalProject_Add(OpenSSL
        PREFIX ${OPENSSL_BUNDLE_DIR}
        GIT_REPOSITORY https://gitee.com/spianmo/openssl-cmake.git
        CMAKE_ARGS
        -DCMAKE_INSTALL_PREFIX=${OPENSSL_BUNDLE_DIR}
        -DANDROID_UNIFIED_HEADERS=ON
        -DCMAKE_TOOLCHAIN_FILE=${CMAKE_ANDROID_NDK}/build/cmake/android.toolchain.cmake
        -DANDROID_ABI=${CMAKE_ANDROID_ARCH_ABI}
        -DANDROID_PLATFORM=android-19
        -DANDROID_TOOLCHAIN=clang
        -DCMAKE_ANDROID_NDK_TOOLCHAIN_VERSION=clang
        BUILD_IN_SOURCE 0
        INSTALL_DIR ${PROJECT_BINARY_DIR}
        BUILD_BYPRODUCTS ${OPENSSL_LIBRARY_SSL} ${OPENSSL_LIBRARY_CRYPTO})

install(FILES "${OPENSSL_LIBRARY_SSL}" DESTINATION "${PROJECT_BINARY_DIR}/lib"
        COMPONENT "libs-deps")
install(FILES "${OPENSSL_LIBRARY_CRYPTO}" DESTINATION "${PROJECT_BINARY_DIR}/lib"
        COMPONENT "libs-deps")
install(DIRECTORY "${OPENSSL_INCLUDE_DIR}" DESTINATION "${PROJECT_BINARY_DIR}/include"
        COMPONENT "libs-deps")

include_directories(${OPENSSL_INCLUDE_DIR})
link_directories(${OPENSSL_BUNDLE_DIR}/lib)

add_library(ssl STATIC IMPORTED GLOBAL)
add_library(crypto STATIC IMPORTED GLOBAL)

set_target_properties(ssl PROPERTIES
        IMPORTED_LOCATION ${OPENSSL_LIBRARY_SSL}
)

set_target_properties(crypto PROPERTIES
        IMPORTED_LOCATION ${OPENSSL_LIBRARY_CRYPTO}
)

add_dependencies(ssl OpenSSL)
add_dependencies(crypto OpenSSL)